package com.ww.springboot.boot.thread.study.executor;

import java.util.concurrent.*;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-04-01 08:54
 */
public class Executor拒绝补偿 {

    private static final ExecutorService executorService = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2));
    private static final ExecutorService executorService2 = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());


    /**
     * 线程池任务被拒绝 会抛出异常,捕获异常后补偿任务(补偿任务使用linkBlockingQueue 因为补偿任务肯定是占少部分的,所以使用无界阻塞队列更合适 避免任务再次被丢弃)即可
     * 极端情况 可能会导致一直被拒绝 所以需要控制补偿上限次数
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            doTask(i);
        }
    }

    private static void doTask(int i) {
        int finalI = i;
        try {
            executorService.submit(() -> {
                System.out.println("开始执行任务"+ finalI);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("结束执行任务"+ finalI);
            });
        } catch (RejectedExecutionException e) {
            executorService2.submit(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                System.out.println("补偿任务"+ finalI);
                doTask(finalI);
            });
        }
    }
}
